package com.tsxy.controller.administrator;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsxy.Exception.MyException;
import com.tsxy.common.APIResult;
import com.tsxy.common.Constants;
import com.tsxy.controller.dto.UserDto;
import com.tsxy.entity.User;
import com.tsxy.service.IUserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 飞
 * @since 2022-02-03
 */
@RestController
@RequestMapping("/user")
public class UserController {

    Log log = LogFactory.get();

    @Resource
    private IUserService userService;

    @PostMapping("/login")
    public APIResult login(@RequestBody UserDto userDto){
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        if ( StrUtil.isBlank(username) || StrUtil.isBlank(password) ){
            return APIResult.error(Constants.CODE_400,"参数不能为空");
        }
            return APIResult.success(userService.login(userDto));
    }
    @PostMapping("/register")
    public APIResult register(@RequestBody UserDto userDto){
        if ( StrUtil.isBlank(userDto.getUsername()) || StrUtil.isBlank(userDto.getPassword()) ){
            return APIResult.error(Constants.CODE_400,"参数不能为空");
        }
        return APIResult.success(userService.register(userDto));
    }
    //新增或者修改
    @PostMapping
    public APIResult save(@RequestBody User user){
        try{
            APIResult success = APIResult.success(userService.saveOrUpdate(user));
            return success;
        }catch (Exception e){
            throw new MyException("500","添加错误");
        }

    }
    //根据id删除
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return userService.removeById(id);
    }
    //批量删除
    @PostMapping("/del/batch")
        public boolean deleteBath(@RequestBody List<Integer> ids){
        return userService.removeByIds(ids);
    }
    //查询所有
    @GetMapping
    public List<User> findAll() {
        return userService.list();
    }
    //根据用户名查询用户
    @GetMapping("/username/{username}")
    public APIResult selectByUserName(@PathVariable("username") String username) {

        return APIResult.success(userService.getByUserName(username));
    }
    //根据id查询
    @GetMapping("/{id}")
        public User findOne(@PathVariable Integer id) {
        return userService.getById(id);
    }
    //分页查询
    @GetMapping("/page")
    public IPage<User> findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String username,
                                @RequestParam(defaultValue = "") String email,
                                @RequestParam(defaultValue = "") String address) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if ( ! "".equals(username)){
            queryWrapper.like("username",username);
        }
        if ( ! "".equals(email)){
            queryWrapper.like("email",email);
        }
        if ( ! "".equals(address)){
            queryWrapper.like("address",address);
        }
        queryWrapper.orderByDesc("id");
        return userService.page(new Page<>(pageNum,pageSize), queryWrapper);
    }
    //导出excel
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        List<User> users = userService.list();
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("aventUrl", "头像地址");

        writer.setOnlyAlias(true);
        writer.merge(8, "用户信息");

        writer.write(users, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");

        ServletOutputStream out=response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //方式一， javaBean的方式读取Excel内的对象 表头如果是中文会报错
        // List<User> users = reader.readAll(User.class);

        //方式2  忽略表头和不插入的字段，自己选择插入的字段
        List<List<Object>> lists = reader.read(1);
        List<User> list = CollUtil.newArrayList();
        for(List<Object> row : lists){
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setNickname(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            user.setAventUrl(row.get(7).toString());
            list.add(user);
        }
        return userService.saveBatch(list);
    }

}

